import xlwt
import json
import os

basePath = os.path.abspath("test_case")

resultUrl = os.path.abspath("xlsx")


# 读取测试用例文件，返回用例的请求和响应数组
def read_json(file_name):
    path = basePath + "\\" + file_name + ".json"
    requests = []
    with open(path, 'r', encoding='utf-8') as fp:
        data = json.load(fp)

    for key in data:
        requests.append(data[key]["request"])
    return requests


# 将测试用例写入json
def write_json(file_name, load_dict):
    path = basePath + "\\" + file_name + ".json"
    with open(path, 'w', encoding='utf8') as write_f:
        json.dump(load_dict, write_f, indent=4, ensure_ascii=False)





# 将数据导入excel文件
def write_xlxs(data, api_type):
    # 创建xlwt表格类型文件，编码格式是utf-8,不压缩
    book = xlwt.Workbook(encoding='utf-8', style_compression=0)

    # 在excel中创建一个sheet表单,名字为test,可重设值
    sheet = book.add_sheet('api_test', cell_overwrite_ok=True)

    # 自定义列名
    col = ('测试用例标识', '优先级', '测试说明', '预置条件', '测试步骤', '预期输出', '实际结果')

    # 将列属性元组col写进sheet表单中
    for i in range(0, 7):
        sheet.write(0, i, col[i])  # 第一个参数是行，第二个参数是列

    # 将数据写进sheet表单中
    for i in range(0, len(data)):
        sheet.write(i, 0, data[i]["identification"])  # 测试用例标识
        sheet.write(i, 1, data[i]["priority"])  # 测试用例标识
        sheet.write(i, 2, data[i]["description"])  # 测试用例标识
        sheet.write(i, 3, data[i]["post_condition"])  # 测试用例标识
        sheet.write(i, 4, data[i]["steps"])  # 测试用例标识
        sheet.write(i, 5, data[i]["expected_output"])  # 测试用例标识
        sheet.write(i, 6, data[i]["result"])  # 测试用例标识

    # 保存excel文件
    savepath = resultUrl + "\\" + api_type.value[0]["file_name"] + ".xlsx"
    book.save(savepath)
